from PIL import Image, ImageEnhance
from StringIO import StringIO

# This function creates a PIL Image from raw image data.
def load_image_from_data(data):
    try:
        sio = StringIO(data)
        image = Image.open(sio)
    except Exception, e:
        raise Exception('Error loading image data, msg="%s"'%e.message)    
    return image
    
# This function extracts the raw image data from a PIL Image. 
def get_data_from_image(image, format = None):
    sio = StringIO()
    image.save(sio, format)
    return sio.getvalue()

def perform(image, factor = '1.0'):
    # Load the image data into a PIL Image.
    pil_image = load_image_from_data(image)

    # Convert the factor to a float.
    factor = float(factor)
    
    # Adjust brightness.
    adjusted_image = ImageEnhance.Brightness(pil_image).enhance(factor)
    
    # Return the image data.
    return get_data_from_image(adjusted_image, pil_image.format)